package com.sh.usercenterbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sh.usercenterbackend.common.BaseResponse;
import com.sh.usercenterbackend.common.ErrorCode;
import com.sh.usercenterbackend.common.ResultUtils;
import com.sh.usercenterbackend.constant.UserConstant;
import com.sh.usercenterbackend.exception.BusinessException;
import com.sh.usercenterbackend.model.User;
import com.sh.usercenterbackend.model.request.UserLoginRequest;
import com.sh.usercenterbackend.model.request.UserRegisterRequest;
import com.sh.usercenterbackend.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.sh.usercenterbackend.constant.UserConstant.ADMIN_ROLE;
import static com.sh.usercenterbackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @Auther: sh
 * @Date: 2024/12/9 20:28
 * @Description: 用户控制器
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
//            return ResultUtils.error(ErrorCode.PARAMS_NULL_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_NULL_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long registerResult = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(registerResult);
    }


    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        System.out.println("请求来了");
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (userAccount == null || userPassword == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User loginResult = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginResult);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request==null){
            return null;
        }
        int userLogout = userService.userLogout(request);
        return ResultUtils.success(userLogout);
    }

    @GetMapping("/getCurrentUser")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {

        HttpSession session = request.getSession();
        if (session == null) {
            log.info("会话不存在");
            return null;
        }
        User currentUser = (User) session.getAttribute(UserConstant.USER_LOGIN_STATE);
        if (currentUser == null) {
            log.info("当前用户未登录");
            return null;
        }
        log.info("当前用户信息: {}", currentUser);
        Long id = currentUser.getId();
        User safeUser = userService.getById(id);
        User resultUser = userService.getSafeUser(safeUser);

//        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
//        if (currentUser == null) {
//            return null;
//        }
////        User safeUser = userService.getSafeUser(currentUser);  // 如果用户信息更新不频繁
//
//        // 如果用户信息更新频繁，则每次查询都重新获取一次
//        Long id = currentUser.getId();
//        User safeUser = userService.getById(id);
//        User resultUser = userService.getSafeUser(safeUser);
        return ResultUtils.success(resultUser);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String userName, HttpServletRequest request) {
        if (!isAdmin(request)) {
            return ResultUtils.success(new ArrayList<>());
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("userName", userName);
        }
        List<User> userList = userService.list(queryWrapper);
        // 脱敏处理
        userList = userList.stream().map(user -> userService.getSafeUser(user)).collect(Collectors.toList());
        return ResultUtils.success(userList);

    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!isAdmin(request)) return ResultUtils.success(false);
        if (id < 0) {
            return ResultUtils.success(false);
        }
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    private boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE) {
            return false;
        }
        return true;
    }


}

